package com.nbcio.pm.controller;

import com.nbcio.common.core.domain.R;
import com.nbcio.common.satoken.utils.LoginHelper;
import com.nbcio.pm.service.IPmProjectService;
import com.nbcio.pm.service.IPmTaskService;
import com.nbcio.pm.service.IPmProjectMemberService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 项目仪表板Controller
 *
 * @author nbacheng
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/pm/dashboard")
@Tag(name = "项目仪表板", description = "项目仪表板相关接口")
public class PmDashboardController {

    private final IPmProjectService projectService;
    private final IPmTaskService taskService;
    private final IPmProjectMemberService projectMemberService;

    /**
     * 获取仪表板统计数据
     */
    @Operation(summary = "获取仪表板统计数据", description = "获取项目仪表板的统计数据")
    @GetMapping("/stats")
    public R<Map<String, Object>> getDashboardStats() {
        Long userId = LoginHelper.getUserId();
        
        Map<String, Object> stats = new HashMap<>();
        
        try {
            // 获取所有项目（不限制用户参与）
            com.nbcio.common.mybatis.core.page.PageQuery pageQuery = new com.nbcio.common.mybatis.core.page.PageQuery();
            pageQuery.setPageNum(1);
            pageQuery.setPageSize(10000); // 设置一个大的页面大小来获取所有数据
            var projectPageResult = projectService.queryPageList(new com.nbcio.pm.domain.bo.PmProjectBo(), pageQuery);
            var allProjects = projectPageResult.getRows();
            log.info("查询到项目总数: {}", allProjects.size());
            int totalProjects = allProjects.size();
            int activeProjects = (int) allProjects.stream().filter(p -> "active".equals(p.getStatus())).count();
            int completedProjects = (int) allProjects.stream().filter(p -> "completed".equals(p.getStatus())).count();
            log.info("项目状态统计 - 进行中: {}, 已完成: {}", activeProjects, completedProjects);
            
            // 获取所有任务（不限制负责人）
            var taskPageResult = taskService.queryPageList(new com.nbcio.pm.domain.bo.PmTaskBo(), pageQuery);
            var allTasks = taskPageResult.getRows();
            log.info("查询到任务总数: {}", allTasks.size());
            int totalTasks = allTasks.size();
            int activeTasks = (int) allTasks.stream().filter(t -> "in_progress".equals(t.getStatus())).count();
            int completedTasks = (int) allTasks.stream().filter(t -> "completed".equals(t.getStatus())).count();
            log.info("任务状态统计 - 进行中: {}, 已完成: {}", activeTasks, completedTasks);
            
            // 获取用户参与的项目（用于我的项目显示）
            var userProjects = projectService.getUserProjects(userId);
            
            // 获取用户的任务（用于我的任务显示）
            var userTasks = taskService.getUserTasks(userId, null);
            
            // 计算任务完成率
            double taskCompletionRate = totalTasks > 0 ? (double) completedTasks / totalTasks * 100 : 0;
            
            // 计算项目平均进度
            double avgProgress = allProjects.stream()
                .filter(p -> p.getProgress() != null)
                .mapToDouble(p -> p.getProgress().doubleValue())
                .average()
                .orElse(0.0);
            
            stats.put("totalProjects", totalProjects);
            stats.put("activeProjects", activeProjects);
            stats.put("completedProjects", completedProjects);
            stats.put("totalTasks", totalTasks);
            stats.put("activeTasks", activeTasks);
            stats.put("completedTasks", completedTasks);
            stats.put("taskCompletionRate", Math.round(taskCompletionRate * 100.0) / 100.0);
            stats.put("avgProgress", Math.round(avgProgress * 100.0) / 100.0);
            
            // 项目状态分布
            Map<String, Integer> projectStatusDistribution = new HashMap<>();
            projectStatusDistribution.put("planning", (int) allProjects.stream().filter(p -> "planning".equals(p.getStatus())).count());
            projectStatusDistribution.put("active", activeProjects);
            projectStatusDistribution.put("completed", completedProjects);
            projectStatusDistribution.put("paused", (int) allProjects.stream().filter(p -> "paused".equals(p.getStatus())).count());
            projectStatusDistribution.put("cancelled", (int) allProjects.stream().filter(p -> "cancelled".equals(p.getStatus())).count());
            log.info("项目状态分布: {}", projectStatusDistribution);
            stats.put("projectStatusDistribution", projectStatusDistribution);
            
            // 任务状态分布
            Map<String, Integer> taskStatusDistribution = new HashMap<>();
            taskStatusDistribution.put("todo", (int) allTasks.stream().filter(t -> "todo".equals(t.getStatus())).count());
            taskStatusDistribution.put("in_progress", activeTasks);
            taskStatusDistribution.put("completed", completedTasks);
            taskStatusDistribution.put("paused", (int) allTasks.stream().filter(t -> "paused".equals(t.getStatus())).count());
            taskStatusDistribution.put("cancelled", (int) allTasks.stream().filter(t -> "cancelled".equals(t.getStatus())).count());
            stats.put("taskStatusDistribution", taskStatusDistribution);
            
            return R.ok(stats);
            
        } catch (Exception e) {
            log.error("获取仪表板统计数据失败", e);
            return R.fail("获取统计数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取我的项目列表（用于仪表板显示）
     */
    @Operation(summary = "获取我的项目列表", description = "获取当前用户的项目列表，用于仪表板显示")
    @GetMapping("/my-projects")
    public R<Object> getMyProjects() {
        try {
            Long userId = LoginHelper.getUserId();
            // 先尝试获取用户参与的项目
            var userProjects = projectService.getUserProjects(userId);
            
            // 如果用户参与的项目为空，则显示所有项目
            if (userProjects.isEmpty()) {
                com.nbcio.common.mybatis.core.page.PageQuery pageQuery = new com.nbcio.common.mybatis.core.page.PageQuery();
                pageQuery.setPageNum(1);
                pageQuery.setPageSize(10000);
                var projectPageResult = projectService.queryPageList(new com.nbcio.pm.domain.bo.PmProjectBo(), pageQuery);
                return R.ok(projectPageResult.getRows());
            }
            
            return R.ok(userProjects);
        } catch (Exception e) {
            log.error("获取我的项目列表失败", e);
            return R.fail("获取项目列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取我的任务列表（用于仪表板显示）
     */
    @Operation(summary = "获取我的任务列表", description = "获取当前用户的任务列表，用于仪表板显示")
    @GetMapping("/my-tasks")
    public R<Object> getMyTasks() {
        try {
            Long userId = LoginHelper.getUserId();
            // 先尝试获取用户的任务
            var userTasks = taskService.getUserTasks(userId, null);
            
            // 如果用户的任务为空，则显示所有任务
            if (userTasks.isEmpty()) {
                com.nbcio.common.mybatis.core.page.PageQuery pageQuery = new com.nbcio.common.mybatis.core.page.PageQuery();
                pageQuery.setPageNum(1);
                pageQuery.setPageSize(10000);
                var taskPageResult = taskService.queryPageList(new com.nbcio.pm.domain.bo.PmTaskBo(), pageQuery);
                return R.ok(taskPageResult.getRows());
            }
            
            return R.ok(userTasks);
        } catch (Exception e) {
            log.error("获取我的任务列表失败", e);
            return R.fail("获取任务列表失败: " + e.getMessage());
        }
    }
}
